//全局使用的变量，在index.html中声明
//全局使用的方法，在此文件声明
import axios from "axios"

import GlobalTools from './GlobalTools.js'//引用模块进来
import { Indicator } from 'mint-ui';
import { MessageBox } from 'mint-ui'

export default {
  GlobalTools: GlobalTools,
  getSignDetailByClass(class_id, startDate, stopDate, callback) {
    var me = this;
    /* startDate = '2019年03月03日';
    stopDate = '2019年03月04日'; */

    startDate = startDate.replace('年', '-').replace('月', '-').replace('日', '');//日期格式必须是 2019-03-19
    if (!stopDate) {
      stopDate = startDate;
    }
    stopDate = stopDate.replace('年', '-').replace('月', '-').replace('日', '');//日期格式必须是 2019-03-19

    axios.all([axios.get("schedule?$orderby=create_time desc&$top=1", { headers: { "Authorization": token } }).then(function (response) { return response.data.value; }).catch(function (error) { }),
    axios.get("rlt_course_class2student?$orderby=create_time desc&$top=1", { headers: { "Authorization": token } }).then(function (response) { return response.data.value; }).catch(function (error) { }),
    ]).then(
      axios.spread(function (schedule, rlt_course_class2student) {

        let scheduleCreatTime = schedule.length > 0 ? new Date(schedule[0].create_time).toISOString() : new Date().toISOString();
        let studentCreatTime = rlt_course_class2student.length > 0 ? new Date(rlt_course_class2student[0].create_time).toISOString() : new Date().toISOString();
        let weekDayStr = (startDate == stopDate) ? ' and weekday eq ' + new Date(startDate).getDay() : '';//如果开始日期和结束日期一样，就是查询当天的

        let url = 'classes?$filter=id eq (' + class_id + ')&$expand=checkin_group($expand=attendance($orderby=checkin_group_id asc,start_time asc)),room($expand=timetable),student($expand=user($filter=activated eq (true);$expand=notice($filter=type eq 6 and state eq 1 and start_date ge ' + new Date(startDate + ' 00:00:00').toISOString() + ' and end_date le ' + new Date(stopDate + ' 23:59:59').toISOString() + '),sign_list($filter=sign_time ge ' + new Date(startDate + ' 00:00:00').toISOString() + ' and sign_time le ' + new Date(stopDate + ' 23:59:59').toISOString() + ';$expand=schedule($expand=room,course_class($expand=course)))),rlt_course_class2student($filter=create_time eq ' + studentCreatTime + ';$expand=course_class($filter=activated eq (true);$expand=course,rlt_course_class2teacher($expand=teacher($expand=user($filter=activated eq (true)))),schedule($filter=create_time eq ' + scheduleCreatTime + weekDayStr + ';$expand=course_class($expand=course),room($expand=timetable))))),course_class($filter=activated eq (true);$expand=course,rlt_course_class2teacher($expand=teacher($expand=user($filter=activated eq (true)))),schedule($filter=create_time eq ' + scheduleCreatTime + weekDayStr + ';$expand=course_class($expand=course),room($expand=timetable)))';

        axios.get(url, { headers: { "Authorization": token } })
          .then((response) => {
            let classList = response.data.value;
            if (classList.length == 0) {
              return null;
            }
            let str = me.parseStudentDetail(classList[0], startDate, stopDate);

            callback(str);

          }).catch(function (error) { })

      })
    )
  },

  //组织每个学生的考勤情况
  parseStudentDetail(classData, startDate, stopDate) {
    //筛选出考勤标尺
    var me = this;
    var timetable = [];
    var attendanceInfo = [];
    var lessionTimetable = [];
    var classScheduleNodes = []; //常规课占用课节
    if (classData.checkin_group && classData.checkin_group.attendance.length > 0) { //班级的日常签到timetable
      attendanceInfo = this.parseAttendance(classData.checkin_group.attendance);
    }
    if (classData.room && classData.room.timetable && classData.room.timetable.content) {//班级所在教室的lession timetable
      lessionTimetable = this.parseLession(classData.room.timetable, classScheduleNodes, classData.student);
    }
    //时间表分组 普通考勤和课节签到: 可两个都显示或只显示一个
    var timetableList = timetable.concat(attendanceInfo, lessionTimetable);
    //this.timetableList = lessionTimetable;
    console.log('全天的作息时间', timetableList);
    var studentDetailList = [];
    if (timetableList.length > 0 && classData.student.length > 0) {
      studentDetailList = classData.student.map(student => {//依次判断所有学生在每个时间段的所有状态
        student.lateList = [];//迟到列表
        student.askForleaveList = [];//请假列表
        student.forgetList = [];//缺卡列表
        student.normalList = [];//正常列表
        student.takeRest = [];//休息天数
        student.sign_date_list = this.getSignTimeDay(student.user.sign_list);//出勤天数
        return this.parseUserStateEveryDay(student, timetableList, startDate, stopDate, classData.course_class);
      });
    }
    return { timetableList: timetableList, studentDetailList: studentDetailList };
  },

  parseAttendance(attendances) {
    let newAttendances = [];
    for (let i = 0; i < attendances.length; i++) {
      //每一个迟到 is_late 都服务于上一个正常的时段
      if (i > 0 && attendances[i].is_late) {
        var j = newAttendances.findIndex(d => d.order == (i - 1));
        if (j > -1)
          newAttendances[j]['late_time'] = attendances[i].start_time;
        newAttendances[j]['late_stop_time'] = attendances[i].stop_time;
      } else {
        //正常: 正常的都push进来
        var tmpAtt = null;
        tmpAtt = attendances[i];
        tmpAtt['sign_start_time'] = tmpAtt['start_time'].split('.')[0];
        tmpAtt['start_time'] = tmpAtt['start_time'].split('.')[0];
        tmpAtt['stop_time'] = tmpAtt['stop_time'].split('.')[0];
        tmpAtt['late_time'] = attendances[i].stop_time;
        tmpAtt['order'] = i;
        tmpAtt['elDisabled'] = false;
        tmpAtt['GID'] = 'A_' + attendances[i].id;
        tmpAtt['type'] = 'att';
        tmpAtt['late_stop_time'] = attendances[i].stop_time;
        newAttendances.push(tmpAtt);
      }
    }
    return newAttendances;
  },

  parseLession(les, classScheduleNodes, student) {
    var lessionInfo = JSON.parse(les.content);
    var lessionTimetable = lessionInfo.filter(data => data.is_lession == 1).map(element => {
      element.GID = 'L_' + element.value;
      element.type = 'schedule';
      var start = new Date('2012-12-12 ' + element.start_time).getTime();
      var stop = new Date('2012-12-12 ' + element.stop_time).getTime();
      var start_time = element.start_time;
      var stop_time = element.stop_time;
      var sign_start_time = new Date(start + (parseInt(les.sign_time_offset) * 60 * 1000) + (1000 * 60 * 60 * 8)).toISOString().substr(11, 8);
      var late_time = new Date(start + (parseInt(les.late_time_offset) * 60 * 1000) + (1000 * 60 * 60 * 8)).toISOString().substr(11, 8);
      var late_stop_time = new Date(stop + (parseInt(les.sign_end_time_offset) * 60 * 1000) + (1000 * 60 * 60 * 8)).toISOString().substr(11, 8);
      var elDisabled = false;
      if (classScheduleNodes.length > 0) {
        elDisabled = (classScheduleNodes.find(d => d.lession == element.value)) ? true : false;
      }
      element['elDisabled'] = elDisabled;
      element.start_time = start_time;
      element.stop_time = stop_time;
      element.sign_start_time = sign_start_time;
      element.late_time = late_time;
      element.late_stop_time = late_stop_time;
      return element;
    });
    lessionTimetable = lessionTimetable.filter(t => { //筛选空课
      if (!t.elDisabled) {
        return student.find(s => {
          if (s.rlt_course_class2student.length > 0) {
            var haveLession = s.rlt_course_class2student.find(r => {
              if (r.course_class && r.course_class.schedule.length > 0) {
                return (r.course_class.schedule.find(d => d.lession_start <= t.value && d.lession_end >= t.value)) ? true : false;
              }
            })
            return haveLession;
          } else { return false; }
        })
      } else { return false; }
    });
    return lessionTimetable;
  },
  //判断学生每一天的考勤状态 查询3月考勤是 2019-03-01 00:00:00    2019-03-01 23:59:59
  parseUserStateEveryDay(student, timetableList, startDate, stopDate, classSchedule) {

    //如果当天是周六或周日，要先判断是否有课程，如果有，就检测刷卡状态；如果没有课，就不作为考勤统计而是作为休息天数
    //判断相差多少天
    let choiceDate = startDate;
    var days = Math.ceil((new Date(stopDate).getTime() - new Date(startDate).getTime()) / (24 * 3600 * 1000));
    for (let i = 0; i <= days; i++) {
      if (i > 0) {
        let timeStr = new Date(new Date(choiceDate).getTime() + 3600 * 24 * 1000);
        choiceDate = timeStr.getFullYear() + '-' + (timeStr.getMonth() + 1) + '-' + timeStr.getDate();
      }
      choiceDate = this.dateFormat(choiceDate, 'date');

      let day = new Date(choiceDate).getDay();
      let hasSchedule = (day == 0 || day == 6) ? 0 : 1; //默认周一至周五有课  周六和周日没课

      //1：是否有班级的课；2：是否有走班课
      if (day == 0 || day == 6) {//周天或者周六
        classSchedule.forEach(course_class => {
          if (course_class.schedule && course_class.schedule.weekDay == day) {
            let scheduleList = this.getTodaySyllabus(course_class.schedule);
            hasSchedule = scheduleList.length;
          }
        })

        if (!hasSchedule && student.rlt_course_class2student.length > 0) {//行政班今天没有课程，检测是否有走班课
          student.rlt_course_class2student.forEach(class2student => {
            if (class2student.course_class.schedule && class2student.course_class.schedule.weekDay == day) {
              let scheduleList = this.getTodaySyllabus(class2student.course_class.schedule);
              hasSchedule = scheduleList.length;
            }
          });
        }
      }

      if (hasSchedule) {
        timetableList.map(timeRange => {
          this.parseUserStateByTime(student, timeRange, choiceDate);
        });
      } else {
        if (!student.takeRest.find(tmp => { return tmp.current_date == choiceDate })) {
          student.takeRest.push({ current_date: choiceDate });
        }
      }
    }

    return student;
  },

  getDaysInMonth(year, month) {
    let temp = new Date(year, month, 0);
    return temp.getDate();
  },

  //判断用户在每一个时间段的考勤状态
  parseUserStateByTime(student, timeRange, choiceDate) {
    //console.log('选择了时间:', timeRange)
    //this.normal = 0; this.takerest = 0; this.leave = 0; this.late = 0;

    var showFlag = timeRange.GID.split('_')[0];
    var tmpObj = {
      time_value: timeRange.GID.split('_')[1],//此值是 attendance 的id，如果是课节签到，这个就是null
      time_type: showFlag == 'A' ? 'att' : 'schedule', // att 就是日常签到， schedule 是课程签到
      late_time: showFlag == 'A' ? timeRange.start_time.split('.')[0] : timeRange.late_time,
      late_time_diff: null,//迟到5分钟
      start_time: timeRange.start_time.split('.')[0],//开始时间
      stop_time: timeRange.stop_time.split('.')[0],//结束时间
      sign_photo: null,
      sign_time: null,
      sign_state: '缺卡',
      current_date: choiceDate,
      /* schedule: {
        lession_start: 1,
        lession_end: 2,//第一至第二节
        course_class: {
          course: {
            id: 1,
            name: '语文'
          },
          rlt_course_class2teacher: [],//知道迟到的这节课是王老师的语文课
        },
      } */
      schedule: null
    };

    //请假
    if (student.user && student.user.notice.length > 0) {
      //signStatus = student.user.notice[0].topic;
      var tmpLeave = student.user.notice.find(d => {
        return new Date(d.start_date).getTime() >= this.getNumberTime(new Date(choiceDate), '00:00:00');
      });
      if (tmpLeave) tmpObj.sign_state = tmpLeave.topic;
    }

    //迟到还是正常
    if (student.user && student.user.sign_list.length > 0) {
      var tmpRes = this.checkStatus(timeRange, student.user.sign_list, choiceDate);
      //赋值
      tmpObj.sign_photo = tmpRes.photo_url;
      //tmpObj.sign_time = (tmpRes.sign_time) ? tmpRes.sign_time.split('T')[1].substr(0, 8) : tmpRes.sign_time;
      tmpObj.sign_time = (tmpRes.sign_time) ? this.dateFormat(tmpRes.sign_time) : tmpRes.sign_time;
      tmpObj.sign_state = tmpRes.signStatus;
      tmpObj.schedule = tmpRes.subject;
      tmpObj.room_name = tmpRes.room_name;
    }

    switch (tmpObj.sign_state) {
      case '正常':
        student.normalList.push(tmpObj);
        // this.normal += 1;
        break;
      case '迟到':
        tmpObj.late_time_diff = ((new Date(tmpObj.sign_time).getTime() - new Date(tmpObj.sign_time.split(' ')[0] + " " + tmpObj.late_time).getTime()) / (60 * 1000)).toFixed(2);
        student.lateList.push(tmpObj);
        // this.late += 1;
        break;
      case '事假': case '病假': case '丧假': case '其他':
        // this.takerest += 1;
        student.askForleaveList.push(tmpObj);
        break;
      case '缺卡':
        // this.leave += 1;
        student.forgetList.push(tmpObj);
        break;
    }


    /* let obj = {
      name: (student.user) ? student.user.name : '查不到用户信息',
      source_id: student.source_id,
      subject: subject,
      room_name: room_name,
      sign_time: signTime,
      sign_status: signStatus
      // photo: studentUrl,
    } */
    //console.log('268行学生数据', student);
    return student;
  },

  checkStatus(timeData, sign_list, choiceDate) {
    var sign_start_time = timeData.sign_start_time;
    var start_time = timeData.start_time;
    var stop_time = timeData.stop_time;
    var late_time = timeData.late_time;//迟到开始时间
    var late_stop_time = timeData.late_stop_time;//迟到截止时间

    //迟到
    var signData = {
      photo_url: null, sign_time: null, signStatus: '缺卡', room_name: null, subject: null, schedule: null
    };
    if (late_time != late_stop_time) {
      var tmpLate = sign_list.find(d => {
        return new Date(d.sign_time).getTime() >= this.getNumberTime(new Date(choiceDate), late_time) && new Date(d.sign_time).getTime() <= this.getNumberTime(new Date(choiceDate), late_stop_time)
      });
      if (tmpLate) {
        tmpLate['signStatus'] = '迟到';
        signData = tmpLate;
      }
    }
    var tmpNormal = sign_list.find(d => {
      return new Date(d.sign_time).getTime() >= this.getNumberTime(new Date(choiceDate), sign_start_time) && new Date(d.sign_time).getTime() <= this.getNumberTime(new Date(choiceDate), late_time);
    });
    if (tmpNormal) {
      tmpNormal['signStatus'] = '正常';
      signData = tmpNormal;
    }
    signData['room_name'] = (signData.schedule)
      ? (signData.schedule.room)
        ? signData.schedule.room.name
        : (signData['signStatus'] == '缺卡') ? null : '未知'
      : (signData['signStatus'] == '缺卡') ? null : '未知';
    signData['subject'] = (signData.schedule)
      ? (signData.schedule.course_class && signData.schedule.course_class.course)
        ? signData.schedule.course_class.course.name
        : (signData['signStatus'] == '缺卡') ? null : '未知'
      : (signData['signStatus'] == '缺卡') ? null : '未知';
    return signData;
  },

  //筛选出今天的所有课程表
  getTodaySyllabus(syllabusInfo, choiceDate) {
    var me = this;
    var today = new Date(choiceDate);
    var setting = me.GlobalTools.settingObj;

    var res = syllabusInfo.filter(schedule => {
      if (schedule.weekday == today.getDay()) {

        // 判断上下学期
        var termStartDate = null;
        if (setting != null) {
          var dates = setting.filter(setting => setting.setting_type == 'first_term' || setting.setting_type == 'second_term').map(setting => setting.setting_data);
          var firstDate = new Date('' + today.getFullYear() + '-' + dates[0] + ' 00:00:00');
          var secondDate = new Date('' + today.getFullYear() + '-' + dates[1] + ' 00:00:00');
          var beforeDate = firstDate.getTime() > secondDate.getTime() ? secondDate : firstDate;
          var afterDate = firstDate.getTime() > secondDate.getTime() ? firstDate : secondDate;
          if (beforeDate.getTime() > today.getTime()) {
            termStartDate = new Date(afterDate.setFullYear(secondDate.getFullYear() - 1));
          } else if (beforeDate.getTime() < today.getTime() && today.getTime() < afterDate.getTime()) {
            termStartDate = beforeDate;
          } else {
            termStartDate = afterDate;
          }
        }
        // 通过学期开始时间计算出到底是哪堂课
        if (termStartDate != null) {
          var startDay = Math.ceil(termStartDate.getTime() / 1000 / 60 / 60 / 24);
          var nowDay = Math.ceil(today.getTime() / 1000 / 60 / 60 / 24);
          var weeks = Math.floor((nowDay - startDay) / 7) + 1;
          if (schedule.start_week <= weeks && weeks <= schedule.end_week) {
            if (schedule.repeat_week == 1) return weeks % 2 == 1;
            else if (schedule.repeat_week == 2) return weeks % 2 == 0;
            else return true;
          } else {
            return false;
          }
        }
        return false;
      }

    });
    return res;

  },
  //获取时间戳
  getNumberTime(base, time) {
    const myTime = new Date('2001-01-01 ' + time);
    myTime.setFullYear(base.getFullYear());
    myTime.setMonth(base.getMonth());
    myTime.setDate(base.getDate());
    // return myTime.getTime() + (1000 * 60 * 60 * 8);
    return myTime.getTime();
  },

  //组织数据格式 date_time 日期时间，date 日期
  dateFormat(timeStr, type = 'date_time') {

    let date = new Date(timeStr);
    let year = date.getFullYear();
    let month = (date.getMonth() + 1) < 10 ? '0' + parseInt(date.getMonth() + 1) : date.getMonth() + 1;
    let day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();

    if (type == 'date_time') {
      let hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
      let minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
      let seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
      return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
    }
    return year + '-' + month + '-' + day;
  },
  //出勤天数
  getSignTimeDay(sign_list) {
    let sign_date_list = [];//具体的出勤日期
    sign_list.forEach(sign => {
      let tmpDate = this.dateFormat(sign.sign_time, 'date');
      if (sign_date_list.indexOf(tmpDate) == -1) {
        sign_date_list.push(tmpDate);
      }
    });
    return sign_date_list;
  },

  // 假条审核 
  verifyPass(me, noticeItem, typeInfo) {
    this.verifyaskleave(1, '{}', noticeItem, me, typeInfo);
  },

  verifyReject(me, noticeItem, typeInfo) {
    let that = this;
    MessageBox.prompt('不予审批', '', {
      inputPlaceholder: '1-50字之间',
      inputValue: '',
      confirmButtonPosition: 'left',
      inputValidator(value) {
        if (value.length < 1 || value.length > 50) {
          return '输入的内容长度应该在1-50之间'
        }
      }
    })
      .then(function (obj, action) {
        that.verifyaskleave(4, obj.value, noticeItem, me, typeInfo);
        return;
      })
      .catch(({ value, action }) => {
        console.log('已取消');
      });
  },

  verifyaskleave(type, reject_desc, noticeItem, me, typeInfo) {
    Indicator.open({
      text: '操作中，请稍后...',
      spinnerType: 'triple-bounce'
    });
    let p = { action: 'verifyaskleave', id: noticeItem.id, user_id: noticeItem.user_id, type: type, content: JSON.stringify({ reason: noticeItem.reason, reject_desc: reject_desc, type: noticeItem.type }), class_id: noticeItem.class_id };
    me.$axios.get(SERVERPROXYURL, { params: p })
      .then(function (response) {
        Indicator.close();
		console.log(p);
		return ;
        if (typeInfo == 1) { //1:成功之后不跳转页面
          me.$router.go(0);
        } else {
          me.$router.go(-1);
        }
      })
      .catch(function (error) {
        debugger;
        console.info(error);
      });
  }
}



